// pages/add/add.js
import utils from '../../utils/util'
import BillUtils from '../../utils/detailsUtil'
import ProjectUtils from '../../utils/projectUtil'
import TypeUtils from '../../utils/typeUtil'
import CensorTextUtil from '../../utils/CensorTextUtil'
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    bill_id: undefined,
    matter: undefined,
    amount: undefined,
    bill_type_index: undefined,
    bill_type: undefined,
    remarks: undefined,
    detail: undefined,
    project_index: undefined,
    project: undefined,
    billDate: undefined,
    year: undefined,
    month: undefined,
    day: undefined,

    TypeList: [],
    ProjectsList: [{
      id: 0,
      project_name: ""
    }],
    isAdd: false
  },
  /**
   * 返回
   */
  Back: function (params) {
    app.globalData.isChoseType = false;
    wx.navigateBack({
      changed: true
    });
  },
  /**
   * 初始化选择器
   * @param {*} params 
   */
  InitSelect: function (params) {
    ProjectUtils.getCanProjects(app.globalData.wxUserInfo.id, (res) => {
      let arr = [{
        id: 0,
        project_name: ""
      }];
      res.data.objects.forEach(item => {
        arr.push(item);
      });
      if (app.globalData.isAddBill) {
        this.setData({
          ProjectsList: arr,
          project_index: 0,
          project: null,
        })
        if (app.globalData.isChoseType) {
          var index = res.data.objects.findIndex(this.checkProjectId)
          if (index != -1) {
            this.setData({
              ProjectsList: arr,
              project_index: index,
              project: res.data.objects[index],
            })
          }
        }
      } else {
        var index = res.data.objects.findIndex(this.checkProjectId)
        if (index == -1) {
          this.setData({
            ProjectsList: arr,
            project_index: 0,
            project: null,
          })
        } else {
          this.setData({
            ProjectsList: arr,
            project_index: index,
            project: res.data.objects[index],
          })
        }
      }
    });
    TypeUtils.getTypes(app.globalData.wxUserInfo.id, null, (res) => {
      if (!app.globalData.isAddBill) {
        var index = res.data.objects.findIndex(this.checkTypeId)
        this.setData({
          TypeList: res.data.objects,
          bill_type_index: index == -1 ? 0 : index,
          bill_type: res.data.objects[index == -1 ? 0 : index],
        })
      } else {
        this.setData({
          TypeList: res.data.objects,
          bill_type_index: 0,
          bill_type: res.data.objects[0],
        })
        if (app.globalData.isChoseType) {
          var index = res.data.objects.findIndex(this.checkTypeId)
          this.setData({
            TypeList: res.data.objects,
            bill_type_index: index == -1 ? 0 : index,
            bill_type: res.data.objects[index == -1 ? 0 : index],
          })
        }
      }
    });
  },
  /**
   * 判断类型id
   * @param {*} item 
   */
  checkTypeId: function (item) {
    return item.id == app.globalData.billInfo.bill_type.id
  },
  /**
   * 判断项目id
   * @param {}} item 
   */
  checkProjectId: function (item) {
    if (app.globalData.billInfo.project) {
      return item.id == app.globalData.billInfo.project.id
    } else {
      return false;
    }
  },
  /**
   * @method: 双向绑定，实时获取输入框值
   * @params: event形参必须有，返回输入框相关对象
   */
  inputedit: function (e) {
    this.setData({
      amount: this.money(e.detail.value) //money匹配金额输入规则，返回输入值
    });
  },
  /**
   * @method: 金额输入限制
   * @params: val接收number值
   */
  money(val) {
    let num = val.toString(); //先转换成字符串类型
    if (num.indexOf('.') == 0) { //第一位就是 .
      num = '0' + num
    }
    num = num.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    if (num.indexOf(".") < 0 && num != "") {
      num = parseFloat(num);
    }
    return num
  },
  /**
   * 金额验证
   * @param {*} e 
   */
  PriceTap: function (e) {
    let num = e.detail.value.toString(); //先转换成字符串类型
    if (num.indexOf('.') == 0) { //第一位就是 .
      num = '0' + num
    }
    num = num.replace(/[^\d.]/g, ""); //清除“数字”和“.”以外的字符
    num = num.replace(/\.{2,}/g, "."); //只保留第一个. 清除多余的
    num = num.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
    num = num.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3'); //只能输入两个小数
    // if (num.indexOf(".") < 0 && num != "") {
    //   num = parseFloat(num);
    // }
    this.setData({
      amount: Number(num)
    })
  },
  /** 
   * 跳转到类型选择
   */
  ChoseType: function (e) {
    app.globalData.isChoseType = true;
    app.globalData.billInfo = {
      id: this.data.bill_id,
      year: this.data.year,
      month: this.data.month,
      day: this.data.day,
      matter: this.data.matter,
      amount: this.data.amount,
      detail: this.data.detail,
      remarks: this.data.remarks,
      project: this.data.project,
      bill_type: this.data.bill_type
    }
    wx.navigateTo({
      url: './choseType/choseType'
    })
  },
  /**
   * 类型选择
   * @param {*} params 
   */
  TypeChange: function (e) {
    this.setData({
      bill_type_index: e.detail.value,
      bill_type: this.data.TypeList[e.detail.value]
    })
  },
  /**
   * 项目选择
   * @param {*} params 
   */
  ProjectChange: function (e) {
    if (e.detail.value == 0) {
      this.setData({
        project_index: e.detail.value,
        project: null
      })
    } else {
      this.setData({
        project_index: e.detail.value,
        project: this.data.ProjectsList[e.detail.value]
      })
    }
  },
  /**
   * 选择日期
   * @param {*} e 
   */
  BillDateChange: function (e) {
    let dateArr = e.detail.value.split('-');
    this.setData({
      year: dateArr[0],
      month: dateArr[1],
      day: dateArr[2]
    })
  },
  /**
   * 保存账单
   * @param {*} params 
   */
  SaveBill: function (params) {
    this.ContentValidation().then(res => {
      console.log(res)
      if (res) {
        if (this.data.isAdd) {
          this.AddBill();
        } else {
          this.EditBill();
        }
        app.globalData.isChoseType = false;
      }
    })
  },
  /**
   * 新增账单
   */
  AddBill: function () {
    BillUtils.addDetail(
      this.data.matter,
      this.data.amount,
      this.data.bill_type,
      this.data.remarks,
      this.data.detail,
      this.data.project,
      this.data.year,
      this.data.month,
      this.data.day, (res) => {
        wx.navigateBack({
          changed: true
        });
      })
  },
  /**
   * 编辑账单
   */
  EditBill: function () {
    BillUtils.updateDetail(
      this.data.bill_id,
      this.data.matter,
      this.data.amount,
      this.data.bill_type,
      this.data.remarks,
      this.data.detail,
      this.data.project,
      this.data.year,
      this.data.month,
      this.data.day, (res) => {
        wx.navigateBack({
          changed: true
        });
      })
  },
  /**
   * 内容验证
   */
  async ContentValidation() {
    const doc = await new Promise((resolve) => {
      var msgItem = []
      let index = 0;
      if (this.data.matter) {
        CensorTextUtil.CensorText(this.data.matter).then(res => {
          if (!res) {
            msgItem.push("账单事项")
          }
          index++;
          this.showMsg(index, msgItem, resolve)
        })
      }
      if (this.data.remarks) {
        CensorTextUtil.CensorText(this.data.remarks).then(res => {
          if (!res) {
            msgItem.push("备注")
          }
          index++;
          this.showMsg(index, msgItem, resolve)
        })
      }
      if (this.data.detail) {
        CensorTextUtil.CensorText(this.data.detail).then(res => {
          if (!res) {
            msgItem.push("账单详情")
          }
          index++;
          this.showMsg(index, msgItem, resolve)
        })
      }
    })
    return doc;
  },
  showMsg(index, msgItem, resolve) {
    if (index == 3) {
      if (msgItem.length > 0) {
        wx.showToast({
          // 提示内容
          title: msgItem.join(",") + "存在违规内容，请重新输入",
          icon: "none",
          duration: 2000,
          mask: false,
        })
        return resolve(false);
      } else {
        return resolve(true);
      }
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.InitSelect();
    this.setData({
      bill_id: null,
      billDate: utils.formatDate(new Date()),
      year: (new Date()).getFullYear(),
      month: (new Date()).getMonth() + 1,
      day: (new Date()).getDate(),
      matter: null,
      amount: null,
      remarks: null,
      detail: null,
      isAdd: app.globalData.isAddBill
    })
    if (app.globalData.billInfo) {
      this.setData({
        bill_id: app.globalData.billInfo.id,
        billDate: app.globalData.billInfo.year + "-" + app.globalData.billInfo.month + "-" + app.globalData.billInfo.day,
        year: app.globalData.billInfo.year,
        month: app.globalData.billInfo.month,
        day: app.globalData.billInfo.day,
        matter: app.globalData.billInfo.matter,
        amount: app.globalData.billInfo.amount,
        remarks: app.globalData.billInfo.remarks,
        detail: app.globalData.billInfo.detail,
        isAdd: app.globalData.isAddBill
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})